import { removeConfigLayout } from "@/utils/cache/local-storage"
import dayjs from "dayjs"
import { FormInstance } from "element-plus"
export interface FormRules {
  required?: boolean
  message: string
  trigger: string
}
/** 格式化时间 */
export const formatDateTime = (time: string | number | Date) => {
  return time ? dayjs(new Date(time)).format("YYYY-MM-DD HH:mm:ss") : "N/A"
}

/** 用 JS 获取全局 css 变量 */
export const getCssVariableValue = (cssVariableName: string) => {
  let cssVariableValue = ""
  try {
    // 没有拿到值时，会返回空串
    cssVariableValue = getComputedStyle(document.documentElement).getPropertyValue(cssVariableName)
  } catch (error) {
    console.error(error)
  }
  return cssVariableValue
}

/** 用 JS 设置全局 CSS 变量 */
export const setCssVariableValue = (cssVariableName: string, cssVariableValue: string) => {
  try {
    document.documentElement.style.setProperty(cssVariableName, cssVariableValue)
  } catch (error) {
    console.error(error)
  }
}

/** 重置项目配置 */
export const resetConfigLayout = () => {
  removeConfigLayout()
  location.reload()
}

export const readImageFile = (file: any) => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.onload = (e: any) => {
      // e.target.result 包含了文件的二进制数据
      resolve(new Uint8Array(e.target.result))
    }
    reader.onerror = (error) => {
      reject(error)
    }
    reader.readAsArrayBuffer(file) // 使用 readAsArrayBuffer 读取二进制数据
  })
}

/**
 * @param label
 * @param required
 * @returns Form表单Rules校验函数
 */
export const generateRule = (label: string, required: boolean = true): FormRules[] => {
  return [
    {
      required,
      message: `${label}不能为空`,
      trigger: "change"
    }
  ]
}

/**
 * 表单重置
 * @param formEl
 */
export const onResetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields && formEl.resetFields()
}

/**
 * 字符串补位
 */
const padStart = (str: string, maxLength: number, fillString = " ") => {
  if (str.length >= maxLength) return str

  const fillLength = maxLength - str.length
  let times = Math.ceil(fillLength / fillString.length)
  while ((times >>= 1)) {
    fillString += fillString
    if (times === 1) {
      fillString += fillString
    }
  }
  return fillString.slice(0, fillLength) + str
}

/**
 * 格式化时间戳
 * @param dateTime 时间戳
 * @param fmt 格式化方式，默认：yyyy-mm-dd HH:mm:ss
 */
export const timeFormat = (dateTime: string | number | null = null, fmt = "yyyy-mm-dd HH:mm:ss") => {
  if (dateTime == "none") return "None"
  if (!dateTime) dateTime = Number(new Date())
  if (dateTime.toString().length === 10) {
    dateTime = +dateTime * 1000
  }

  const date = new Date(dateTime)
  let ret
  const opt: any = {
    "y+": date.getFullYear().toString(), // 年
    "m+": (date.getMonth() + 1).toString(), // 月
    "d+": date.getDate().toString(), // 日
    "h+": date.getHours().toString(), // 时
    "M+": date.getMinutes().toString(), // 分
    "s+": date.getSeconds().toString() // 秒
  }
  for (const k in opt) {
    ret = new RegExp("(" + k + ")").exec(fmt)
    if (ret) {
      fmt = fmt.replace(ret[1], ret[1].length == 1 ? opt[k] : padStart(opt[k], ret[1].length, "0"))
    }
  }
  return fmt
}

/**
 * 格式化时间戳
 * @param key 排序的key
 * @param t 布尔 传入false则是从小到大排列
 */
export const compare = (key: string, t: boolean) => {
  return function (a: any, b: any) {
    let value1 = a[key]
    let value2 = b[key]
    if (t == true) {
      // 大到小排列
      return value1 - value2
    } else {
      // 小到大排列
      return value2 - value1
    }
  }
}

//
export const getDayAll = (starDay: string, endDay: string) => {
  var arr = []
  var dates = []
  // 设置两个日期UTC时间
  var db = new Date(starDay)
  var de = new Date(endDay)
  // 获取两个日期GTM时间
  var s = db.getTime() - 24 * 60 * 60 * 1000
  var d = de.getTime() - 24 * 60 * 60 * 1000
  // 获取到两个日期之间的每一天的毫秒数
  for (var i = s; i <= d; ) {
    i = i + 24 * 60 * 60 * 1000
    arr.push(parseInt(i))
  }
  // 获取每一天的时间  YY-MM-DD
  for (var j in arr) {
    var time = new Date(arr[j])
    var year = time.getFullYear()
    var mouth = time.getMonth() + 1 >= 10 ? time.getMonth() + 1 : "0" + (time.getMonth() + 1)
    var day = time.getDate() >= 10 ? time.getDate() : "0" + time.getDate()
    var YYMMDD = year + "/" + mouth + "/" + day
    dates.push(YYMMDD)
  }
  return dates
}

//订单数据过滤
export const orderFiltering = (data: any) => {
  let newData = {
    x: [] as string[],
    yCount: [] as number[],
    yNopayData: [] as number[],
    yPayData: [] as number[]
  }
  for (const key in data) {
    newData.x.push(key)
    newData.yCount.push(data[key].bill_date_count)
    newData.yNopayData.push(data[key].bill_date_count_nopay)
    newData.yPayData.push(data[key].bill_date_count_pay)
  }
  return newData
}
